package com.sec.bnjey.database;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

public class DiagHistoryDbUtil {

	static final String DATABASE_TABLE = "diag_history";

	public static final String PKEY = "PKEY";
	public static final String WORK_TIME = "WORK_TIME";
	public static final String CAR_NAME = "CAR_NAME";
	public static final String WORK_NAME = "WORK_NAME";
	public static final String CODE_COUNT = "CODE_COUNT";
	public static final String FORWARD_STATUS = "FORWARD_STATUS";

	static final String CREATE_QUERY = "CREATE TABLE " + DATABASE_TABLE
			+ " (PKEY INTEGER PRIMARY KEY AUTOINCREMENT, " + WORK_TIME
			+ " TEXT, " + CAR_NAME + " TEXT, " + WORK_NAME + " TEXT, "
			+ CODE_COUNT + " INTEGER, " + FORWARD_STATUS + " INTEGER)";

	private SQLiteDatabase mDatabase;

	DiagHistoryDbUtil(SQLiteDatabase db) {
		mDatabase = db;
	}

	public synchronized long insert(DiagHistoryInfo info) {
		ContentValues args = new ContentValues();
		args.put(WORK_TIME, info.getWorkTime());
		args.put(CAR_NAME, info.getCarName());
		args.put(WORK_NAME, info.getWorkName());
		args.put(CODE_COUNT, info.getCodeCount());
		args.put(FORWARD_STATUS, info.getForwardStatus());
		return mDatabase.insert(DATABASE_TABLE, null, args);
	}

	public synchronized boolean remove(long key) {
		return mDatabase.delete(DATABASE_TABLE, PKEY + "=" + key, null) > 0;
	}

	public synchronized boolean removeAll() {
		return mDatabase.delete(DATABASE_TABLE, null, null) > 0;
	}

	private Cursor getAll() {
		return mDatabase.query(DATABASE_TABLE, new String[] { PKEY, WORK_TIME,
				CAR_NAME, WORK_NAME, CODE_COUNT, FORWARD_STATUS }, null, null,
				null, null, WORK_TIME + " DESC");
	}

	public synchronized ArrayList<DiagHistoryInfo> getInfoList() {
		ArrayList<DiagHistoryInfo> list = new ArrayList<DiagHistoryInfo>();
		DiagHistoryInfo info;
		Cursor cursor = getAll();
		cursor.moveToFirst();
		while (!cursor.isAfterLast()) {
			info = new DiagHistoryInfo();
			info.setPkey(cursor.getInt(0));
			info.setWorkTime(cursor.getString(1));
			info.setCarName(cursor.getString(2));
			info.setWorkName(cursor.getString(3));
			info.setCodeCount(cursor.getInt(4));
			info.setForwardStatus(cursor.getInt(5));
			list.add(info);
			cursor.moveToNext();
		}
		cursor.close();
		return list;
	}

	public synchronized boolean setForwardStatus(int index) {
		ContentValues updateStatus = new ContentValues();
		updateStatus.put(FORWARD_STATUS, 1);
		mDatabase.update(DATABASE_TABLE, updateStatus, PKEY + " = " + index,
				null);
		return true;
	}

	private String getCurrentDate() {
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat(
				"yyyy-MM-dd HH:mm:ss");
		Date date = new Date();
		return simpleDateFormat.format(date).toString();
	}

}
